const { router } = require("../app")

const user = require('../dataBase/userModule')
var md5 = require('md5')
require('dotenv').config()

const jwt = require("jsonwebtoken");



const list = async (req, res) => {
    let data = await user.getUserlist()
    res.json({
        code: 200,
        data,
    })
}

//注册
const add = async (req, res) => {
    //接收参数  进行验证、
    if (!req.body.name || !req.body.password) {
        res.json({
            code: -1,
            msg: '用户名或密码不能为空'
        })
        return
    }
    //处理密码为加密
    console.log(process.env.PASSWORD_SECRET);

    req.body.password = md5(md5(req.body.password) + process.env.PASSWORD_SECRET)
    let result = await user.addUser(req.body)
    if (result.affectedRows === 1) {
        res.json({
            code: 200,
            msg: '注册成功',
            id: result.insertId,
        })
    } else {
        res.json({
            code: -1,
            msg: '注册失败',
        })
    }
}
//登录
const login = async (req, res) => {
    let { name, password } = req.body;
    let result = await user.getUserbyNameAndPassword(
        name,
        md5(md5(password) + process.env.PASSWORD_SECRET)
    );
    if (result.length === 0) {
        res.json({
            code: -1,
            msg: '用户名或密码错误，若没有账号请先注册',
        });
        return;
    } else {
        let token = jwt.sign({ ...result[0] }, process.env.JWT_SECRET, {
            expiresIn: "24h"
        });
        // console.log(token);res.json({
        res.json({
            code: 1,
            msg: '登录成功',
            token,
        });
    }
};


// const del = (req, res) => {
//     res.json({ msg: 'ok' })
// }

// const update = (req, res) => {
//     res.json({ msg: 'ok' })
// }


// const search = (req, res) => {
//     res.json({ msg: 'ok' })
// }

module.exports = {
    // list,
    add,
    login,
    // del,
    // update,
    // search,
}